<template>
  <div class="editor relative h-1/1 bg-[#f4f4f4]">
    <div class="sticky z-10 top-0 h-[100px] bg-[#fff]">
      <div class="h-[54px]">
        <editorHeader @get-url="insertMaterial" v-bind="$attrs"></editorHeader>
      </div>
      <div class="py-7px whitespace-nowrap flex flex-1">
        <div class="toolbar m-auto">
          <Toolbar :editor="editorRef" :mode="props.mode" :default-config="props.toolbarConfig"></Toolbar>
        </div>
      </div>
    </div>
    <div class="relative bg-[#f4f4f4]">
      <div class="max-w-[1600px] w-[90%] m-auto">
        <edit-set v-model:group="pageInConfig.group" v-model:cover="pageInConfig.cover" v-bind="$attrs"></edit-set>
        <div class="w-[768px] mt-[30px] mx-auto bg-[#fff]" style="box-shadow: 0 1px 5px 0 rgb(0 0 0 / 5%)">
          <div id="editor-height" class="min-h-[calc(100vh-130px)] pt-[30px] pb-[72px] px-[95px]">
            <div>
              <div class="pt-[20px] pb-[5px] px-0 relative">
                <el-input
                  type="textarea"
                  v-model="pageInConfig.title"
                  placeholder="请输入标题"
                  :maxlength="64"
                  :autosize="true"
                  resize="none"
                  class="text-24px outline-none border-[0px] w-1/1 leading-1 whitespace-pre-line pr-98px"
                ></el-input>
                <div class="absolute top-[32px] transform right-0">
                  <span>{{ pageInConfig.title.length }}/64</span>
                </div>
              </div>
              <div class="px-0 relative" v-if="pageInConfig.author">
                <el-input
                  :maxlength="8"
                  type="text"
                  placeholder="请输入作者"
                  v-model="pageInConfig.author"
                  class="text-15px outline-none border-[0px] w-1/1 leading-1 pr-80px"
                />
                <div class="absolute right-0 top-[50%] transform translate-y-[-50%]">
                  <span>{{ pageInConfig.author.length }} / 8</span>
                </div>
              </div>
            </div>
            <Editor
              :default-config="props.editorConfig"
              v-model="pageInConfig.cont"
              class="mt-[10px] overflow-hidden"
              id="liang-editor"
              :mode="props.mode"
              @on-created="handleCreated"
            ></Editor>
          </div>
        </div>
      </div>
      <bottomVue @publish="publish"></bottomVue>
    </div>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css";
import { onBeforeUnmount, reactive, shallowRef, watch } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IToolbarConfig, IEditorConfig, SlateTransforms, Boot } from "@wangeditor/editor";
import editSet from "./components/editorSet.vue";
import editorHeader from "./components/header.vue";
import buildCard from "./node/buildCard";
import bottomVue from "./components/bottom.vue";
import { ElMessage } from "element-plus";

// 页面内的文章配置
const pageInConfig = reactive({
  title: "",
  author: "",
  cont: "",
  cover: "", //文章封面
  group: 0, //文章分类
  hasVideo: false //
});

interface BaseInfo {
  title?: string;
  author?: string;
  cont?: string;
  cover?: string;
  group?: number;
  hasVideo?: boolean;
}

// 编辑器配置
interface RichEditorProps {
  baseInfo?: BaseInfo;
  toolbarConfig?: Partial<IToolbarConfig>; // 工具栏配置 ==> 非必传（默认为空）
  editorConfig?: Partial<IEditorConfig>; // 编辑器配置 ==> 非必传（默认为空）
  mode?: "default" | "simple"; // 富文本模式 ==> 非必传（默认为 default）
  hideToolBar?: boolean; // 是否隐藏工具栏 ==> 非必传（默认为false）
  disabled?: boolean; // 是否禁用编辑器 ==> 非必传（默认为false）
}

// 编辑器实例
const editorRef = shallowRef();

const props = withDefaults(defineProps<RichEditorProps>(), {
  baseInfo() {
    return {
      title: "",
      author: "",
      cont: "",
      cover: "",
      hasVideo: false
    };
  },
  toolbarConfig() {
    return {
      excludeKeys: ["group-video", "code", "codeBlock", "group-image"]
    };
  },
  editorConfig() {
    return {
      placeholder: "从这里开始写正文......",
      MENU_CONF: {},
      autoFocus: true,
      withCredentials: true
    };
  }
});

// 实列化编辑器
const handleCreated = (editor: any) => {
  editorRef.value = editor;
  Boot.registerModule(buildCard);
};

// 插入多图片
const insertImage = (val: any) => {
  let nodeList = [];
  for (let i = 0; i < val.data.length; i++) {
    const node = { type: "image", src: val.data[i].origin_name, style: { width: "100%" }, children: [{ text: "" }] };
    nodeList.push(node);
  }
  SlateTransforms.insertNodes(editorRef.value, nodeList);
};
// 插入视频
const insertVideo = (val: any) => {
  let nodeList = [];
  for (let i = 0; i < val.data.length; i++) {
    const node = {
      type: "video",
      src: val.data[i].origin_name,
      poster: val.data[i].cover,
      style: { width: "100%" },
      children: [{ text: "" }]
    };
    console.log(node);
    nodeList.push(node);
  }
  SlateTransforms.insertNodes(editorRef.value, nodeList);
};

// 插入楼盘
const insertLou = (val: any) => {
  const data = val.data;
  let disadvantage_name = "";
  let disadvantage_cover = "";
  let disadvantage_color = "";
  if (data.disadvantage && data.disadvantage.length != 0) {
    disadvantage_name = data.disadvantage[0].name;
    disadvantage_cover = data.disadvantage[0].cover;
    disadvantage_color = data.disadvantage[0].textColor;
  }
  console.log(data);
  const node = {
    type: "build-card",
    id: data.id,
    title: data.name,
    address: data.belong_name.split("-")[2],
    tags: data.tags
      ? data.tags
          .map((e: any) => e)
          .splice(0, 3)
          .join(",")
      : "",
    price: data.reference_price,
    cover: data.cover,
    status: data.status_name,
    status_background: data.status_color,
    status_color: data.status_text_color,
    area: `建面：${data.min_area}-${data.max_area}m²`,
    disadvantage_name,
    disadvantage_color,
    disadvantage_cover,
    children: [{ text: "" }]
  };
  const p = { type: "paragraph", children: [{ text: "" }] };
  SlateTransforms.insertNodes(editorRef.value, [node, p]); //必须插入一个p标签不然无法编辑
};

// 插入素材
const insertMaterial = (val: any) => {
  // 移动光标到指定位置
  editorRef.value.focus();
  if (val.fileType === "image") {
    insertImage(val);
  } else if (val.fileType === "video") {
    insertVideo(val);
  } else if (val.fileType === "card") {
    insertLou(val);
  }
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  if (!editorRef.value) return;
  editorRef.value.destroy();
});

// 判断是否有视频
const hasVideo = () => {
  return editorRef.value.getEditableContainer().getElementsByTagName("video").length > 0;
};

// 发表
const emits = defineEmits(["save"]);
const publish = () => {
  pageInConfig.hasVideo = hasVideo();
  emits("save", pageInConfig);
  ElMessage.success("发表成功");
  setTimeout(() => {
    window.close();
  }, 500);
};

// 监听
watch(
  () => props.baseInfo,
  () => {
    pageInConfig.author = props.baseInfo.author as string;
    pageInConfig.cont = props.baseInfo.cont as string;
    pageInConfig.title = props.baseInfo.title as string;
    pageInConfig.group = props.baseInfo.group as number;
    pageInConfig.cover = props.baseInfo.cover as string;
    pageInConfig.hasVideo = props.baseInfo.hasVideo as boolean;
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
